﻿using Furion.CMS.Core;
using Furion.CMS.Core.EventSource;
using Furion.CMS.Core.Handlers;
using Furion.DatabaseAccessor;
using Furion.EventBus;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Furion.CMS.Domain
{
    public class SiteSettingFormatHandler<T> : AuditLogFormatHandler
    {
        public override string[] GetChangeValue(DbContext context, object oldValue, object newValue)
        {
            var oldValueStr = oldValue?.ToString() ?? "";
            var newValueStr = newValue?.ToString() ?? "";
            var oldModel = oldValueStr.ToModel<T>() ?? Activator.CreateInstance<T>();
            var newModel = newValueStr.ToModel<T>();

            var results = oldModel.ToCompare<T>(newModel);
            return new string[2] { results.OldResult, results.NewResult };
        }
    }

    /// <summary>
    /// 站点设置
    /// </summary>
    [OperateRecord("站点设置")]
    public class SiteSetting : Entity,
        IEntityTypeBuilder<SiteSetting>,
        IEntitySeedData<SiteSetting>,
        IEntityChangedListener<SiteSetting>
    {
        public SiteSetting()
        {
            CreatedTime = DateTimeOffset.UtcNow;
        }

        /// <summary>
        /// 站点名称
        /// </summary>
        [MaxLength(100), Required]
        [OperateRecord("站点名称")]
        public string Name { get; set; }
        /// <summary>
        /// 站点标题
        /// </summary>
        [MaxLength(200), Required]
        [OperateRecord("站点标题")]
        public string Title { get; set; }
        /// <summary>
        /// 站点Logo
        /// </summary>
        [MaxLength(200)]
        public string Logo { get; set; }
        /// <summary>
        /// 网址地址
        /// </summary>
        [MaxLength(200)]
        [OperateRecord("网址地址")]
        public string HostUrl { get; set; }
        /// <summary>
        /// 关键词
        /// </summary>
        [MaxLength(800)]
        public string Keywords { get; set; }
        /// <summary>
        /// 描述
        /// </summary>
        [MaxLength(800)]
        public string Description { get; set; }
        /// <summary>
        /// 版权信息
        /// </summary>
        [MaxLength(200)]
        public string Copyright { get; set; }
        /// <summary>
        /// 是否启用安全锁定
        /// </summary>
        [OperateRecord("是否启用安全锁定")]
        public bool IsSafeLock { get; set; }
        /// <summary>
        /// 安全锁定时长
        /// </summary>
        [OperateRecord("安全锁定时长")]
        public int SafeLockDuration { get; set; }
        /// <summary>
        /// 安全验证最大失败次数
        /// </summary>
        [OperateRecord("安全验证最大失败次数")]
        public int SafeVerifyMaxFialNumber { get; set; }
        /// <summary>
        /// 是否启用登录验证码
        /// </summary>
        [OperateRecord("是否启用登录验证码")]
        public bool IsLoginCaptcha { get; set; }
        /// <summary>
        /// 是否启用双因素验证
        /// </summary>
        [OperateRecord("是否启用双因素验证")]
        public bool IsTwoFactorVerify { get; set; }
        /// <summary>
        /// 是否启用手机号登录验证
        /// </summary>
        [OperateRecord("是否启用手机号登录验证")]
        public bool IsPhoneNumberLogin { get; set; }
        /// <summary>
        /// 验证码有效时长
        /// </summary>
        [OperateRecord("验证码有效时长")]
        public int CaptchaDuration { get; set; }
        /// <summary>
        /// 对象存储模式
        /// </summary>
        [OperateRecord("对象存储模式")]
        public StorageMode ObjectStorageMode { get; set; }
        /// <summary>
        /// 对象存储接入参数
        /// </summary>
        [OperateRecord("对象存储接入参数", typeof(SiteSettingFormatHandler<ObjectStorageParams>))]
        public ObjectStorageParams ObjectStorageParam { get; set; }
        /// <summary>
        /// 短信服务提供商
        /// </summary>
        [OperateRecord("短信服务提供商")]
        public SmsServerProviders SmsServerProvider { get; set; }
        /// <summary>
        /// 短信服务接入参数
        /// </summary>
        [OperateRecord("短信服务接入参数", typeof(SiteSettingFormatHandler<SmsAccessParams>))]
        public SmsAccessParams SmsAccessParam { get; set; }

        public void Configure(EntityTypeBuilder<SiteSetting> entityBuilder, DbContext dbContext, Type dbContextLocator)
        {
            entityBuilder.UseDefaultTableNameDefine();

            entityBuilder.OwnsOne(p => p.ObjectStorageParam);
            entityBuilder.OwnsOne(p => p.SmsAccessParam);
        }

        public IEnumerable<SiteSetting> HasData(DbContext dbContext, Type dbContextLocator)
        {
            var seedData = new List<SiteSetting>();
            seedData.Add(new SiteSetting
            {
                Id = 1,
                Name = "Furion CMS",
                Title = "Furion CMS Pro",
                Copyright = "Copyright © 2021-2022 Furion CMS",
                IsSafeLock = true,
                SafeVerifyMaxFialNumber = 5,
                SafeLockDuration = 300,
                IsPhoneNumberLogin = true,
                CaptchaDuration = 180,
            });

            return seedData;
        }

        public void OnChanged(SiteSetting newEntity, SiteSetting oldEntity, DbContext dbContext, Type dbContextLocator, EntityState state)
        {
            // 触发事件
            var eventPublisher = App.GetService<IEventPublisher>();
            eventPublisher?.PublishAsync(new OnTriggerOuterEvent(OuterEventCategory.SettingsUpdate));
        }
    }
}
